package com.skynet.supervision.exceptions;

import cn.hutool.core.text.StrFormatter;
import com.skynet.supervision.common.Result;
import com.skynet.supervision.common.ResultGeneric;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import javax.annotation.Nonnull;
import java.util.Optional;

@EqualsAndHashCode(callSuper = true)
@ToString
public class CheckedException extends Exception {
    @Getter
    private final Result error;

    public CheckedException(Result error) {
        super(Optional.ofNullable(error)
                .map(e -> StrFormatter.format("code:{},msg:{},data:{}",
                        error.getCode(),
                        error.getMessage(),
                        error.getData()))
                .orElse("wtf? error is null..."));
        this.error = error;
    }


    public Result unwrap() {
        return this.error;
    }

    public static CheckedException wrap(@Nonnull Result error) {
        return new CheckedException(error);
    }

    public static CheckedException wrap(@Nonnull ResultGeneric<?> error) {
        return new CheckedException(Result.wrapGeneric(error));
    }
}
